package com.easycarebn.main.fragment;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.telephony.SmsMessage;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.easycarebn.main.utils.IResult;
import com.easycarebn.main.utils.Utils;
import com.easycarebn.request.controller.ServerController;
import com.easycarebn.request.data.DataItemResponse;
import com.easycarebn.request.data.Regiter;
import com.easycarebn.request.data.StatusCode;
import com.easycarebn.request.data.UserProfile;
import com.easycarebn.request.data.UserResponse;
import com.easycarebn.service.request.OnRequest;
import com.timbacsi.main.EasyCareApplication;
import com.timbacsi.main.R;

public class FragmentRegister extends Fragment {

	private View mView;
	private static FragmentRegister fragment = null;
	private IResult callIResult;
	private static String mTitle;

	private EditText edPhone;
	private EditText edFullName;
	
	private EditText edCode;
	private EditText edPhoneActive;

	private ProgressBar mLoadding;

	private TextView lblDangnhap;
	private LinearLayout lineStep1;
	private LinearLayout lineStep2;
	public BroadcastReceiver mybroadcast = new TextMessageReceiver();
	private String mPhone;
	private String mFullName;
	
	public static FragmentRegister newInstance(Bundle data) {
		fragment = new FragmentRegister();
		fragment.setArguments(data);
		return fragment;
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		if (activity instanceof IResult) {
			callIResult = (IResult) activity;
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mView = inflater.inflate(R.layout.frangment_register, null);

		return mView;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		mTitle = getArguments().getString(Utils.KEY_TITLE);
        mPhone = getArguments().getString(Utils.KEY_PHONE);
        
		Utils.setTitlePage(mView, mTitle);
		callIResult.onDisplay(Utils.TASK_CHILD, "");
		Utils.setOnTouchHideKeyboard(getActivity(), (ViewGroup) mView);
		edPhone = (EditText) mView.findViewById(R.id.edPhone);
		edFullName = (EditText) mView.findViewById(R.id.edFullName);
		
		edCode = (EditText) mView.findViewById(R.id.edCode);
		edPhoneActive = (EditText) mView.findViewById(R.id.edPhoneActive);

		mLoadding = (ProgressBar) mView.findViewById(R.id.loadding);
		lblDangnhap = (TextView) mView.findViewById(R.id.lblDangnhap);
		lineStep1 = (LinearLayout) mView.findViewById(R.id.line_register_step1);
		lineStep2 = (LinearLayout) mView.findViewById(R.id.line_register_step2);

		

		if (mTitle.equalsIgnoreCase(getResources().getString(
				R.string.kich_hoat_tai_khoan))) {
			lineStep2.setVisibility(View.VISIBLE);
			lineStep1.setVisibility(View.GONE);
		} else {
			lineStep2.setVisibility(View.GONE);
			lineStep1.setVisibility(View.VISIBLE);

		}

		// Demo dang ky
		Button lblNhanlaima = (Button) mView.findViewById(R.id.lblNhanlaima);
		lblNhanlaima.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mPhone.isEmpty()) {
					edPhoneActive.setVisibility(View.VISIBLE);
					mPhone = edPhoneActive.getText().toString();
					if (mPhone.isEmpty()) {
						Utils.showMessage(getActivity(), getResources()
								.getString(R.string.vui_long_nhap_so_dt_nhan_ma));
						return;
					}

					if (mPhone.length() < 10 || mPhone.length() > 11) {
						Utils.showMessage(getActivity(), getResources()
								.getString(R.string.so_dien_thoai_ko_hop_le));
						return;
					}

				}

				mLoadding.setVisibility(View.VISIBLE);
				Utils.disableEnableControls(false, mView);
				ServerController.getInstance(getActivity())
						.requestdoResendActiveCode(mPhone,
								new OnRequest<DataItemResponse>() {

									@Override
									public void onSuccess(DataItemResponse data) {
										mLoadding.setVisibility(View.GONE);
										Utils.disableEnableControls(true, mView);
										if (data.getCode() == StatusCode.OK) {
											Utils.showMessage(
													getActivity(),
													getResources()
															.getString(
																	R.string.ma_kich_hoat_dc_gui_lai));
										}
									}

									@Override
									public void onError(int errorCode,
											String message) {
										mLoadding.setVisibility(View.GONE);
										Utils.disableEnableControls(true, mView);
									}
								});

			}
		});

		Button btnDangky = (Button) mView.findViewById(R.id.btnDangky);

		btnDangky.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mFullName = edFullName.getText().toString().trim();
				if (mFullName.isEmpty()) {
					Utils.showMessage(
							getActivity(),
							getResources().getString(
									R.string.nhap_ho_ten));
					return;
				}
				mFullName=mFullName.replace(" ", "%20"); 
				
				mPhone = edPhone.getText().toString().trim();
				if (mPhone.isEmpty()) {
					Utils.showMessage(
							getActivity(),
							getResources().getString(
									R.string.vui_long_nhap_so_dt));
					return;
				}

				if (mPhone.length() < 10 || mPhone.length() > 11) {
					Utils.showMessage(
							getActivity(),
							getResources().getString(
									R.string.so_dien_thoai_ko_hop_le));
					return;
				}
				mLoadding.setVisibility(View.VISIBLE);
				Utils.disableEnableControls(false, mView);

				ServerController.getInstance(getActivity()).requestRegister(
						mPhone,mFullName, new OnRequest<DataItemResponse>() {

							@Override
							public void onSuccess(DataItemResponse data) {
								mLoadding.setVisibility(View.GONE);
								Utils.disableEnableControls(true, mView);
								if (data.getCode() == StatusCode.OK) {
									lineStep1.setVisibility(View.GONE);
									lineStep2.setVisibility(View.VISIBLE);
									Utils.showMessage(getActivity(),String.format(getActivity().
											getResources().getString(
													R.string.ma_xa_thuc_da_dc_gui),mPhone));
									
								
								}
							}

							@Override
							public void onError(int errorCode, String message) {
								Utils.showMessage(getActivity(), message);
								mLoadding.setVisibility(View.GONE);
								Utils.disableEnableControls(true, mView);
							}
						});

			}
		});
		Button btnActive = (Button) mView.findViewById(R.id.btnActive);
		btnActive.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				actionActivee();
			}
		});

		lblDangnhap.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				callIResult.onDisplay(Utils.LOGIN,
						getResources().getString(R.string.lblDangnhap));
			}
		});

	}

	public void actionActivee() {

		String mCode = edCode.getText().toString().trim();
		if (mCode.isEmpty()) {
			Utils.showMessage(getActivity(),
					getResources().getString(R.string.vui_long_nhap_so_ma_kh));
			return;
		}
		mLoadding.setVisibility(View.VISIBLE);
		Utils.disableEnableControls(false, mView);
		ServerController.getInstance(getActivity()).requestActiveRegister(
				mCode, new OnRequest<Regiter>() {

					@Override
					public void onSuccess(Regiter data) {
						mLoadding.setVisibility(View.GONE);
						Utils.disableEnableControls(true, mView);
						if (data.getCode() == StatusCode.OK) {
							UserResponse user = new UserResponse();
							user.setToken(data.getToken());

							UserProfile userProfile = new UserProfile();
							userProfile.setFull_name(data.getFullName());
							userProfile.setPhone(mPhone);

							user.setUser(userProfile);
							EasyCareApplication mEaApplication = (EasyCareApplication) getActivity()
									.getApplicationContext();
							mEaApplication.setLogin(true);

							Utils.updateUserLogin(getActivity(), user);
							callIResult.onDisplay(
									Utils.SHOW_HOME,
									getResources().getString(
											R.string.lblDangnhap));
						} else {
							Utils.showMessage(getActivity(), getResources()
									.getString(R.string.ma_xa_thuc_khong_dung));
						}

					}

					@Override
					public void onError(int errorCode, String message) {
						mLoadding.setVisibility(View.GONE);
						Utils.disableEnableControls(true, mView);
					}
				});

	}

	@Override
	public void onPause() {
		getActivity().unregisterReceiver(mybroadcast);
		super.onPause();
	}

	@Override
	public void onResume() {
		IntentFilter filter = new IntentFilter();
		filter.addAction("android.provider.Telephony.SMS_RECEIVED");
		getActivity().registerReceiver(mybroadcast, filter);
		super.onResume();
	}

	public class TextMessageReceiver extends BroadcastReceiver {

		public void onReceive(Context context, Intent intent) {
			Bundle bundle = intent.getExtras();

			Object[] messages = (Object[]) bundle.get("pdus");
			SmsMessage[] sms = new SmsMessage[messages.length];

			for (int n = 0; n < messages.length; n++) {
				sms[n] = SmsMessage.createFromPdu((byte[]) messages[n]);
			}

			try {
				for (SmsMessage msg : sms) {

					String arrays[] = msg.getMessageBody().split(
							"Easycare. Ma kich hoat tai khoan cua ban la");
					String s = arrays[1].toString().trim();

					String code[] = s.split(" ");

					edCode.setText(code[0]);
					actionActivee();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
